package com.ytjj.qmyx.admin.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ytjj.common.exception.ApiException;
import com.ytjj.common.utils.HttpClientUtil;
import com.ytjj.qmyx.admin.config.SupplyApiConfig;
import com.ytjj.qmyx.admin.dao.ReturnGoodsDao;
import com.ytjj.qmyx.admin.eunm.FreightStatusEnum;
import com.ytjj.qmyx.admin.eunm.ModuleEnum;
import com.ytjj.qmyx.admin.eunm.ReasonTypeEnums;
import com.ytjj.qmyx.admin.eunm.ReturnDutyTypeEnum;
import com.ytjj.qmyx.admin.mapper.ReturnDutyMapper;
import com.ytjj.qmyx.admin.model.ReturnDuty;
import com.ytjj.qmyx.admin.model.ReturnDutyExample;
import com.ytjj.qmyx.admin.model.dto.ReturnDutyDto;
import com.ytjj.qmyx.admin.model.response.ReturnGoodsResponse;
import com.ytjj.qmyx.admin.service.AdminModuleLogService;
import com.ytjj.qmyx.admin.service.ReturnDutyService;
import com.ytjj.qmyx.admin.service.ReturnRegisterService;
import com.ytjj.qmyx.mall.mapper.OrdersInfoMapper;
import com.ytjj.qmyx.mall.mapper.ReturnGoodsMapper;
import com.ytjj.qmyx.mall.model.OrdersInfo;
import com.ytjj.qmyx.mall.model.ReturnGoods;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

/**
 * 
 * 
 * @Version: 1.0
 */
@Slf4j
@Service
public class ReturnDutyServiceImpl implements ReturnDutyService {

    @Resource
    private ReturnDutyMapper returnDutyMapper;

    @Resource
    private ReturnGoodsDao returnGoodsDao;

    @Resource
    private OrdersInfoMapper ordersInfoMapper;

    @Resource
    private SupplyApiConfig supplyApiConfig;
    @Resource
    private AdminModuleLogService adminModuleLogService;

    @Override
    public ReturnDutyDto getReturnDuty(ReturnDutyDto param) {
        if (null == param.getServiceNo() && null == param.getChildOrderNo()) {
            throw new ApiException("服务号和子订单不能同时为空!");
        }
        ReturnDuty rd = BeanUtil.copyProperties(param, ReturnDuty.class);
        rd.setDelFlag(null);
        ReturnDuty returnDuty = returnDutyMapper.selectOne(rd);
        ReturnDutyDto returnDutyDto = BeanUtil.copyProperties(returnDuty, ReturnDutyDto.class);


        if (null != returnDutyDto.getOrderInfoId()) {
            OrdersInfo ordersInfo = ordersInfoMapper.selectByPrimaryKey(returnDutyDto.getOrderInfoId());
            if (null != ordersInfo && null != ordersInfo.getIsRefund()) {
                returnDutyDto.setIsRefund(ordersInfo.getIsRefund().intValue());
            }
        }
        return returnDutyDto;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveReturnDuty(ReturnDutyDto param) {
        log.info("============saveReturnDuty===========param:{}",JSONObject.toJSONString(param));
        ReturnGoodsResponse returnGoods = returnGoodsDao.selectByServiceNo(param.getServiceNo());
        if (null == returnGoods) {
            log.info("没有找到对应的服务单号!");
            throw new ApiException("没有找到对应的服务单号!");
        }

        param.setOrderNo(returnGoods.getOrderNo());
        param.setOrderInfoId(returnGoods.getOrdersInfoId());
        param.setChildOrderNo(returnGoods.getChildOrderNo());
        param.setRecvName(returnGoods.getUserName());
        param.setRecvPhone(returnGoods.getUserPhone());
        param.setAfterType(returnGoods.getAfterType());
        if (StringUtils.isBlank(param.getExpressNo()) ) {
            param.setExpressNo(returnGoods.getExpressNo());
        }
        if (StringUtils.isBlank(param.getReturnTradeNo()) ) {
            param.setReturnTradeNo(returnGoods.getReturnExpressNo());
        }
        ReturnDuty returnDuty = BeanUtil.copyProperties(param, ReturnDuty.class);
        getFreightStatus(returnDuty);
        param.setAfterSaleStatus(0);
        if (null != param.getOrderType() && null != param.getReasonType() && null != param.getReasonSecondType()) {
            param.setAfterSaleStatus(1);
        }
        log.info("============saveReturnDuty===========returnDuty:{}",JSONObject.toJSONString(returnDuty));
        if(null != param.getReturnDutyFee()){
            //更新售后数据
            ReturnGoods newReturnGood = new ReturnGoods();
            newReturnGood.setServiceNo(param.getServiceNo());
            newReturnGood.setAmount(param.getReturnDutyFee());
            returnGoodsDao.updateByServiceNo(newReturnGood);
        }
        returnDutyMapper.insertSelective(returnDuty);
        try {
            String resultJson = HttpClientUtil.doPostJson(supplyApiConfig.getUrl() + "/returnDuty/saveOrUpdateReturnDuty",
                    JSONObject.toJSONString(returnDuty), supplyApiConfig.getHeadsMap());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void updateDutyDel(Integer orderInfoId,String serviceNo,String childOrderNo) {
        try {
            log.info("修改退货责任标记 orderInfoId:{}", orderInfoId);
            ReturnDuty updateDelDuty = new ReturnDuty();
            updateDelDuty.setOrderInfoId(orderInfoId);
            updateDelDuty.setDelFlag(1);
            returnDutyMapper.updateDuty(updateDelDuty);
            adminModuleLogService.recordReturnDuty(updateDelDuty,ModuleEnum.RETURN_DUTY.getType(),2,serviceNo,childOrderNo);
        } catch (Exception e) {
            log.info("修改退货责任失败 orderInfoId: {}", orderInfoId);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateReturnDuty(ReturnDutyDto param) {
        param.setAfterSaleStatus(0);
        if (null != param.getOrderType() && null != param.getReasonType() && null != param.getReasonSecondType() && StringUtils.isNotBlank(param.getReasonDetail())) {
            param.setAfterSaleStatus(1);
        }
        ReturnDuty returnDuty = BeanUtil.copyProperties(param, ReturnDuty.class);
        getFreightStatus(returnDuty);
        returnDutyMapper.updateByPrimaryKeySelective(returnDuty);
        ReturnGoods returnGoods = new ReturnGoods();
        returnGoods.setServiceNo(param.getServiceNo());
        if(null != param.getReturnDutyFee()){
            //修改退款金额
            returnGoods.setAmount(param.getReturnDutyFee());
        }
        returnGoods.setReasonType(param.getReasonTypeText());
        returnGoods.setReturnReason(param.getReasonSecondTypeText());
        returnGoodsDao.updateByServiceNo(returnGoods);
        ReturnGoodsResponse returnGoodsResponse = returnGoodsDao.selectByServiceNo(param.getServiceNo());
        adminModuleLogService.recordReturnDuty(returnDuty, ModuleEnum.RETURN_DUTY.getType(),2,param.getServiceNo(),returnGoodsResponse.getChildOrderNo());
        try {
            String resultJson = HttpClientUtil.doPostJson(supplyApiConfig.getUrl() + "/returnDuty/saveOrUpdateReturnDuty",
                    JSONObject.toJSONString(returnDuty), supplyApiConfig.getHeadsMap());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void getFreightStatus(ReturnDuty returnDuty) {
        log.info("判断退运费状态修改 returnDuty: {}", JSON.toJSONString(returnDuty));
        Integer freightStatus = returnDuty.getFreightStatus();
        if (null != freightStatus && FreightStatusEnum.FINISH.getCode() == freightStatus) {
            returnDuty.setFreightStatus(freightStatus);
            return;
        }
        Integer freightDuty = returnDuty.getFreightDuty();
        if (null == freightDuty) { return; }
        if (ReturnDutyTypeEnum.WH.getCode() == freightDuty || ReturnDutyTypeEnum.WH_CUS.getCode() == freightDuty
                || ReturnDutyTypeEnum.CUS.getCode() == freightDuty) {
            returnDuty.setFreightStatus(FreightStatusEnum.NO_DUTY.getCode());
        } else if (ReturnDutyTypeEnum.PLAT_WH.getCode() == freightDuty || ReturnDutyTypeEnum.PLAT.getCode() == freightDuty) {
            returnDuty.setFreightStatus(FreightStatusEnum.WAIT.getCode());
        }
    }



}
